package com.example.newsapp.utils;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.example.newsapp.activity.LoginActivity;
import com.example.newsapp.model.Result;
import com.google.gson.Gson;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.concurrent.TimeUnit;

public class HttpUtil {
    private static final String TAG = "HttpUtil";
    private static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
    private static final OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(5, TimeUnit.SECONDS)
            .readTimeout(5, TimeUnit.SECONDS)
            .build();
    private static final Gson gson = new Gson();

    public interface Callback<T> {
        void onSuccess(T result);
        void onFailure(Exception e);
    }

    public static <T> void request(Context context,String url, String method, @Nullable Object requestObj, Type typeOfT, Callback<T> callback) {
        new Thread(() -> {
            try {
                Request.Builder builder = new Request.Builder().url(url);
                String token = UserSessionUtil.getToken(context);
                if (token != null && !token.isEmpty()) {
                    builder.addHeader("Authorization",token);
                }
                if ("GET".equalsIgnoreCase(method)) {
                    builder.get();
                } else if ("POST".equalsIgnoreCase(method)) {
                    RequestBody body = RequestBody.create(gson.toJson(requestObj), JSON);
                    builder.post(body);
                } else if ("PUT".equalsIgnoreCase(method)) {
                    RequestBody body = RequestBody.create(gson.toJson(requestObj), JSON);
                    builder.put(body);
                } else if ("DELETE".equalsIgnoreCase(method)) {
                    if (requestObj != null) {
                        RequestBody body = RequestBody.create(gson.toJson(requestObj), JSON);
                        builder.delete(body);
                    } else {
                        builder.delete();
                    }
                }

                Response response = client.newCall(builder.build()).execute();
                if (response.code() == 401) {
                    UserSessionUtil.logout(context);
                    runOnUiThread(() -> {
                        Toast.makeText(context, "登录已过期，请重新登录", Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(context, LoginActivity.class);
                        context.startActivity(intent);
                    });
                    return;
                }
                String responseBody = response.body().string();
                T result = gson.fromJson(responseBody, typeOfT);
                runOnUiThread(() -> callback.onSuccess(result));
            } catch (Exception e) {
                runOnUiThread(() -> callback.onFailure(e));
            }
        }).start();
    }

    private static void runOnUiThread(Runnable r) {
        new Handler(Looper.getMainLooper()).post(r);
    }
}
